package com.aliang.book_java1.Task;




import com.alibaba.fastjson.JSON;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import oshi.driver.linux.proc.CpuInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.util.Util;

import java.util.HashMap;
import java.util.Map;


@Component
@EnableScheduling
public class TaskJob {
    // 静态锁,保证重复运行只启动一次
    private static  Boolean LOCK_TASK = true;
    /**
     * 等待休眠时间，单位ms
     */
    private static final int WAIT_TIME_MS = 1000;
    //5秒一次
    @Scheduled(cron = "0/5 * * * * ?")
    public void task() {
        if(!LOCK_TASK){
            return;
        }
        LOCK_TASK=false;

        /*定时任务一定要加异常捕捉，因为Scheduled一般是单线程的（当然可以配置成多线程），
          防止执行报错导致定时任务不执行，捕捉异常的话不会影响下次执行*/
        try {
            oshi.SystemInfo si = new oshi.SystemInfo();
            CentralProcessor processor = si.getHardware().getProcessor();
            // CPU信息
            long[] prevTicks = processor.getSystemCpuLoadTicks();
            Util.sleep(WAIT_TIME_MS);
            long[] ticks = processor.getSystemCpuLoadTicks();
            long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
            long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
            long softIrq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
            long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
            long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
            long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
            long ioWait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
            long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
            long totalCpu = user + nice + cSys + idle + ioWait + irq + softIrq + steal;

            Map<String,Object> infoMap=new HashMap<>();
            infoMap.put("核心数",processor.getLogicalProcessorCount());
            infoMap.put("CPU总的使用率",totalCpu);
            infoMap.put("CPU系统使用率",cSys);
            infoMap.put("CPU用户使用率",user);
            infoMap.put("CPU当前等待率",ioWait);
            infoMap.put("CPU当前空闲率",idle);
            //简单输出（此处可以记录到日志，持久化到库，或者添加到队列用websocket推送到前端展示）
            System.out.println("-----"+ JSON.toJSONString(infoMap));
            LOCK_TASK=true;
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
